/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief Implementation for ObjectDB interface client library.
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * $Id: ObjectDBClient.cpp,v 1.4 2009-10-23 13:56:43 morsko Exp $
 *
 */

#include "ObjectDBClient.hpp"
#include "ObjectDBData.hpp"

//*****************************************************************************
using namespace MaCI::ObjectDB;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CObjectDBClient::CObjectDBClient(gimi::GIMI *aGIMIPtr, 
                           const int aInterfaceMinor)
  : CSync(1,1), // Max One Mutex, Max one Condition
    CThread(1), // Max one Thread.
    CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_OBJECTDB, aInterfaceMinor),
    iObjectDBDataSequence(0),
    iObjectDBCommandSequence(0),
    iLastObjectDBData(),
    iObjectDBClientCallback(NULL)
{
  dPrint(4,"CObjectDBClient %p constructed", this);
}
//*****************************************************************************

CObjectDBClient::~CObjectDBClient()
{
  DoClose();
  dPrint(4,"CObjectDBClient %p destructed", this);
}
//*****************************************************************************

MaCI::EMaCIError CObjectDBClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();

    // If all inits were fine...
    if (result == KMaCIOK) {
      // Start the Thread
      SetActive(true);
      EnableSynchronousMessageReply();
      CThread::RunThread();
      dPrint(4,"CObjectDBClient::DoOpen() was succesfull.");
    }

  } else {
    dPrint(4,"ObjectDBClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CObjectDBClient::DoClose(void)
{
  EMaCIError result = KMaCIError;
  
  if(IsActive()) {
    SetActive(false);

    // Wait for thread to complete.
    CThread::SetRequestTermination();
    /* CThread::CancelThread(); //Removed by script */
    CThread::WaitThread();
    result = UnsubscribeToInterface(TimeoutValue(2000));
  
    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed ObjectDBClient");    
    }else{
      dPrint(4,"Unsubscribing failed at ObjectDBClient!");
    }
    
    
    
  } else {
    dPrint(4, "ObjectDBClient not active, so not Closing.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

TDBObjectHandle CObjectDBClient::GenerateRealObject(const std::string &aName,
                                                    const std::string &aType,
                                                    const std::string &aDescription,
                                                    const unsigned int aTimeout_ms)
{
  TDBObjectHandle result_handle = 0; // error

  // Mark start of operation point for timeout calculation.
  const ownTime_ms_t call_begin = ownTime_get_ms();


  // Construct Query object.
  CObjectDBData query;
  query.CreateInternalBinBag();
  query.SetCommand(TCommand(KCommandGenerateRealObject,0));
  query.SetDBObjectNameString(aName);
  query.SetDBObjectTypeString(aType);
  query.SetDBObjectDescriptionString(aDescription);


  // Get Uniq id for query.
  const unsigned int query_id = GetUniqueMessageID();


  // Send the command.
  SendCommand(query, query_id);


  // Receive reply.
  CObjectDBData reply;
  const ownTime_ms_delta_t call_timeleft = ownTime_get_ms_left(aTimeout_ms, call_begin);
  if (call_timeleft > 0) {
    if (GetCommandReply(reply, query_id, call_timeleft)) {
      // GetCommandReply was succesfull.
      const TCommand *cmdreply = reply.GetCommand();
      if (cmdreply->cmd == KCommandGenerateRealObject &&
          cmdreply->flags & KFlagReply) {
        // Got reply OK - store ID!
        result_handle = cmdreply->data;
        
      } else {
        // Quck. Invalid contents.

      }
    } else {
      // Quck. No reply :( ObjectDB instance is sad.
      
    }
  }


  return result_handle;
}
//*****************************************************************************

bool CObjectDBClient::GetCommandReply(CObjectDBData &aData, const int aMessageID, 
                                   const int aTimeout_ms)
{ 
  EMaCIError result;
  SMessageSource ms; // Compulsory for call to
                     // Receivesynchronousmessagereply, not used here
                     // though.

  // Call the ReceiveMessage wrapper with timeout
  result = ReceiveSynchronousMessageReply(aData, ms, aMessageID, aTimeout_ms);
  
  // If result is OK, process the msg.
  if (result == KMaCIOK) {
    // Got message OK.  Basicly we don't need to do anything here, but
    // some interface may want to do some checks: for example, the
    // received message contains some specific element or information
    // before it is accepted.
  }
  
  return (result == KMaCIOK);
}
//*****************************************************************************

bool CObjectDBClient::SendCommand(const CObjectDBData &aObjectDBData, const int aMessageID)
{
  EMaCIError result = KMaCIError;
  
  if (IsActive()) {
    if (aObjectDBData.GetCommand()) {
      // Send.
      SendInterfaceMessage(aObjectDBData.GetBinBagContainerPtr()->GetBuffer(),
                           aObjectDBData.GetBinBagContainerPtr()->GetBufferSize(),
                           aMessageID);
      
      dPrint(10,"SendInterfaceMessage called: %d:%d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             aObjectDBData.GetBinBagContainerPtr()->GetBufferSize());
      // Result
      result = KMaCIOK;
      
    } else {
      dPrint(2,"No 'TCommand' element in provided CObjectDBData object. Will not send!");
      result = KMaCIInvalidFormat;

    }
   
  } else {
    dPrint(2,"Unable to send ObjectDBData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }


  return (result == KMaCIOK);
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

int CObjectDBClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CObjectDBData id;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = id.DecodeFrom(&bb);
    if (r) {
      // Succesfully decoded as ObjectDB, now handle contents
      Lock();
#warning Fix mee
      /*      if (id.GetObjectDBEvent()) {
        iLastObjectDBData = id;
        ++iObjectDBDataSequence;
        Notify(KEventObjectDBData);
        dPrint(10,"Got ObjectDBData, Sequence now %u", iObjectDBDataSequence);
        }*/
      Unlock();
      
      // Call the handler if set.
      if (iObjectDBClientCallback) {
        dPrint(8,"Got Callback for ObjectDBDataEvent - executing!");
        iObjectDBClientCallback->OnObjectDBDataEvent(id,
                                               iObjectDBDataSequence,
                                               *this);
        dPrint(8,"Callback for ObjectDBDataEvent - execution complete!");
      } 

    } else {
      dPrint(4,"WARNING: Received ObjectDB interface message, but failed to decode as ObjectDBData!");
      
    }
  }
  
  return result;
}

//*****************************************************************************

int CObjectDBClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  const unsigned int hard_error_count_limit = 10;
  unsigned int hard_error_count = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000);
    if (e == KMaCIOK) {
      ProcessMessage(gmsg);

      // Reset error counter.
      if (hard_error_count) hard_error_count = 0;

    } else if (e != KMaCITimeout) {
      // Increment hard error count
      ++hard_error_count;
      
      // Check whether the hard error count limit is still under limit. 
      if (hard_error_count < hard_error_count_limit) {
        // Other error, try to recover by sleeping one second.
        dPrint(10,"ProcessMessage returned error %u, trying to recover by sleeping 1000ms (%u attempts left)",
               e, hard_error_count_limit-hard_error_count);
        ownSleep_ms(1000);

      } else {
        dPrint(3,"Error Recovery failed, ObjectDBClient ThreadFunction terminating...");

        // Break the while().
        break;
      }
      
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");
  SetActive(false);

  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
